//
//  HMHorizontalGridView.m
//  01-横向网格控件制作
//
//  Created by teacher on 2017/7/24.
//  Copyright © 2017年 teacher. All rights reserved.
//

#import "HMHorizontalGridView.h"
#import <Masonry/Masonry.h>
#import <SDWebImage/UIImageView+WebCache.h>

@interface HMHorizontalGridViewLayout : UICollectionViewLayout

// 行
@property (assign, nonatomic)   NSInteger    row;

// 列
@property (assign, nonatomic)   NSInteger   column;

@end

@interface HMHorizontalGridViewLayout ()

@property (assign, nonatomic)   CGSize  contentSize;

@property (strong, nonatomic)   NSMutableArray<UICollectionViewLayoutAttributes *>  *collectionViewLayoutAttributeses;

@end

@implementation HMHorizontalGridViewLayout

#pragma mark - 属性重写 -
- (NSMutableArray<UICollectionViewLayoutAttributes *> *)collectionViewLayoutAttributeses {
    if(_collectionViewLayoutAttributeses == nil) {
        
        _collectionViewLayoutAttributeses = [NSMutableArray array];
    }
    return _collectionViewLayoutAttributeses;
}

#pragma mark - 私有方法 -
// 总共项的数量
- (NSInteger)numberOfItems {
    return [self.collectionView numberOfItemsInSection:0];
}

// 总共页数
- (NSInteger)numberOfPages {
    NSInteger itemCount = [self numberOfItems];
    // 先获取总共 item 数量
    return itemCount % (self.row * self.column) == 0 ? (itemCount / (self.row * self.column)) : ((itemCount / (self.row * self.column)) + 1);
}


#pragma mark - 自定义布局重写方法 -
// 用于预计算一些具体所要的数据
// 如：contentSize
- (void)prepareLayout {
    
    NSInteger pageCount = [self numberOfPages];
    
    // 1. 计算contentSize
    self.contentSize = CGSizeMake(self.collectionView.frame.size.width * pageCount, self.collectionView.frame.size.height);
    
    // 2. 计算好所有 cell UICollectionViewLayoutAttributes 属性对象的集合 装入 collectionViewLayoutAttributeses 集合
    // 定义当前 第几个 cell 的下标
    NSInteger itemIdx = 0;
    
    // 过滤下标越界
    NSInteger itemCount = [self numberOfItems];
    
    for (int pageIdx = 0; pageIdx <  pageCount; pageIdx ++) {
        for (int rowIdx = 0; rowIdx < self.row; rowIdx ++) {
            for (int columnIdx = 0; columnIdx < self.column; columnIdx ++) {
                
                
                itemIdx = pageIdx * self.column * self.row + self.column * rowIdx + columnIdx;
                
                
                // 布局属性 应该 对应 哪个 cell
                UICollectionViewLayoutAttributes *layoutAttributes = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:[NSIndexPath indexPathForRow:itemIdx  inSection:0]];
                
                // 计算布局属性对象的frame值
                CGFloat width = self.collectionView.frame.size.width / self.column;
                CGFloat height = self.collectionView.frame.size.height / self.row;
                
                // 之前page的宽度 + 在当前page中的位置
                CGFloat x = pageIdx * self.collectionView.frame.size.width + width * columnIdx;
                
                // 当前在page中的位置
                CGFloat y = rowIdx * height;
                layoutAttributes.frame = CGRectMake(x, y, width, height);
                
                [self.collectionViewLayoutAttributeses addObject:layoutAttributes];
                
                if(itemIdx >= itemCount - 1) break;
            }
            if(itemIdx >= itemCount - 1) break;
        }
        if(itemIdx >= itemCount - 1) break;
    }
    
    
}

// 返回具体collectionView contentSize
- (CGSize)collectionViewContentSize {
    return self.contentSize;
}

// 返回当前可见界面中具体有哪些 cell
- (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect {
    // rect 表示当前可见区域
    
    NSMutableArray *attributeses = [NSMutableArray array];
    
    [self.collectionViewLayoutAttributeses enumerateObjectsUsingBlock:^(UICollectionViewLayoutAttributes * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if(CGRectIntersectsRect(obj.frame, rect) ) {
            [attributeses addObject:obj];
        }
    }];
    return attributeses;
}

@end


@interface HMHorizontalGridViewCell : UICollectionViewCell

@property (strong, nonatomic)   UIImageView     *iconImageView;

@property (strong, nonatomic)   UILabel         *titleLabel;

@property (weak, nonatomic)     HMHorizontalGridView    *horizontalGridView;

@property (assign, nonatomic)   NSInteger       idx;


@end

@implementation HMHorizontalGridViewCell

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.contentView.backgroundColor = [UIColor clearColor];
        self.backgroundColor = [UIColor clearColor];
        self.titleLabel = [UILabel new];
        self.titleLabel.font =[UIFont systemFontOfSize:13];
        self.titleLabel.textAlignment = NSTextAlignmentCenter;
        [self.contentView addSubview:self.titleLabel];
        [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.bottom.equalTo(self.contentView);
            make.height.mas_equalTo(20);
        }];
        
        
        self.iconImageView = [UIImageView new];
        self.iconImageView.clipsToBounds = YES;
        self.iconImageView.contentMode = UIViewContentModeScaleAspectFill;
        self.iconImageView.layer.cornerRadius = 50 / 2;
        [self.contentView addSubview:self.iconImageView];
        [self.iconImageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.size.mas_equalTo(CGSizeMake(50, 50));
            make.centerX.equalTo(self.contentView);
            make.bottom.equalTo(self.titleLabel.mas_top).mas_offset(-10);
        }];
        
        UITapGestureRecognizer *gr = [[UITapGestureRecognizer alloc] initWithTarget:self
                                                                             action:@selector(actionTap:)];
        [self.contentView addGestureRecognizer:gr];
        
    }
    return self;
}


- (void)actionTap:(UITapGestureRecognizer *)gr {
    // 获取当前
    if(self.horizontalGridView.delegate && [self.horizontalGridView.delegate respondsToSelector:@selector(horizontalGridView:didSelectItemAtIndex:)]) {
        [self.horizontalGridView.delegate horizontalGridView:self.horizontalGridView didSelectItemAtIndex:self.idx];
    }
}

@end


@interface HMHorizontalGridView () <UICollectionViewDataSource,UICollectionViewDelegate>


@property (strong, nonatomic)   UICollectionView    *collectionView;

@end

@implementation HMHorizontalGridView

#pragma mark - 属性重写 -
- (UICollectionView *)collectionView {
    if(_collectionView == nil) {
        HMHorizontalGridViewLayout *layout = [HMHorizontalGridViewLayout new];
        
        NSInteger row = 2;
        NSInteger column = 5;
        if(self.delegate && [self.delegate respondsToSelector:@selector(rowOfPerPageInHorizontalGridView:)]) {
            row = [self.delegate rowOfPerPageInHorizontalGridView:self];
        }
        if(self.delegate && [self.delegate respondsToSelector:@selector(columnOfPerPageInHorizontalGridView:)]) {
            column = [self.delegate columnOfPerPageInHorizontalGridView:self];
        }
        
        layout.row =  row;
        layout.column = column;
        
        
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
        _collectionView.backgroundColor = [UIColor clearColor];
        _collectionView.pagingEnabled = YES;
        _collectionView.showsVerticalScrollIndicator = NO;
        _collectionView.showsHorizontalScrollIndicator = NO;
        
        [_collectionView registerClass:[HMHorizontalGridViewCell class] forCellWithReuseIdentifier:@"CELL"];
        
        _collectionView.dataSource = self;
        _collectionView.delegate = self;
        
        
        [self addSubview:_collectionView];
        
        [_collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self);
        }];
    }
    return _collectionView;
}

#pragma mark - 公共方法 -
- (void)reloadData {
    [self.collectionView reloadData];
}

#pragma mark - UICollectionViewDataSource -
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    NSInteger count = 0;
    if(self.dataSource && [self.dataSource respondsToSelector:@selector(numberOfItemsInHorizontalGridView:)]) {
        count = [self.dataSource numberOfItemsInHorizontalGridView:self];
    }
    return count;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    HMHorizontalGridViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"CELL" forIndexPath:indexPath];
    
    if(self.dataSource && [self.dataSource respondsToSelector:@selector(horizontalGridView:titleForItemAtIndex:)]) {
        cell.titleLabel.text = [self.dataSource horizontalGridView:self titleForItemAtIndex:indexPath.row];
    }
    if(self.dataSource && [self.dataSource respondsToSelector:@selector(horizontalGridView:urlForItemAtIndex:)]) {
        if(self.placeholderIconImage != nil) {
            [cell.iconImageView sd_setImageWithURL:[self.dataSource horizontalGridView:self urlForItemAtIndex:indexPath.row] placeholderImage:self.placeholderIconImage];
        } else {
            [cell.iconImageView sd_setImageWithURL:[self.dataSource horizontalGridView:self urlForItemAtIndex:indexPath.row]];
        }
    } else {
        if(self.placeholderIconImage != nil) {
            cell.iconImageView.image = self.placeholderIconImage;
        }
    }
    cell.horizontalGridView = self;
    cell.idx = indexPath.row;
    
    return cell;
}

@end
